#-*-coding:utf-8-*-
import os
import sys
import platform
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *
from Widgets.rename import Rename
from Widgets.delete_warn import DeleteWarn
from Windows.CreateProject import CreateProject

class RadioWidget(QWidget):
    name_Signal=Signal(str)#当前选择的项目，发射信号
    # create_Signal=Signal(str)#创建项目时发射的信号，该信号应该不用，因为直接从CreateProject中创建
    del_Signal=Signal(str)#删除项目时发射的信号
    projectName_projectPath_Signal=Signal(tuple)#既然要给主界面刷新部门，(current_project_name,real_project_path,departmentList)
    # 后面估计还要刷新集数、镜头。先把数据给计算出来

    def  __init__(self,parent=None):
        super(RadioWidget,self).__init__()
        #全局变量
        current_dir=os.path.dirname(__file__)
        # print('parent:',self.parent())
        self.PROJECT_INFO_PATH=parent.PROJECT_INFO_PATH#os.path.join(os.path.dirname(current_dir),'projects')

        self.mainLayout=QVBoxLayout()
        # self.mainLayout.setAlignment(Qt.AlignTop)

        self.scrollArea = QScrollArea()  # 滚动窗口，需要添加self.scroll_widget进来
        self.scroll_widget=QWidget()#滚动窗口添加的内组件
        self.scroll_layout=QVBoxLayout()#滚动组件self.scroll_widget的布局，这里动态添加radiobutton
        self.scroll_layout.setAlignment(Qt.AlignTop)

        # self.mainLayout.addWidget(self.scrollArea)
        self.radio_project_list=[]#总的项目列表


        self.mainLayout.addWidget(self.scrollArea)

        #添加右击菜单
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.__rightMenu)

        self.current_project=''


    def setRadioBtnList(self,nameList):
        self.radio_project_list=nameList

        for i in range(self.scroll_layout.count()): #先把以前的列表删除干净
            self.scroll_layout.itemAt(i).widget().deleteLater()

        for i in nameList:
            radio_btn=QRadioButton(i)

            # radio_btn.setStyleSheet("hover{color:#FF6600}")

            radio_btn.setStyleSheet("QRadioButton:hover{color :#FF6600}")
            radio_btn.clicked.connect(self.__showNameSlot)
            # radio_btn.clicked.connect(self.run)
            self.scroll_layout.addWidget(radio_btn)

        self.scroll_widget.setLayout(self.scroll_layout)#添加布局
        self.scrollArea.setWidget(self.scroll_widget)

        self.setLayout(self.mainLayout)


    def deleteCurrentRadioBtn(self):
        '''
        因为是RadioButton所以除非一开始为空，必然选中的就是当前的，所以该方法可以直接调用
        :return:
        '''
        if self.current_project is not '':
            self.radio_project_list.remove(self.current_project)
            for i in range(self.scroll_layout.count()):
                self.scroll_layout.itemAt(i).widget().deleteLater()
            self.__removeProject(self.current_project)
            self.setRadioBtnList(self.radio_project_list)
        else:
            QMessageBox.information(self, '提示', '请先选择项目')


    def __showNameSlot(self):
        btn=self.sender()
        name=btn.text()
        self.current_project=name
        real_project_path=self.getRealProjectPath(self.current_project)
        try:
            os.listdir(real_project_path)
            department_list=os.listdir(real_project_path)
            temp_tuple=(self.current_project,real_project_path,department_list)

            self.projectName_projectPath_Signal.emit(temp_tuple)
        except:
            self.projectName_projectPath_Signal.emit(())
            print('空目录')



    def renameBtn(self):
        '''
        打开重命名窗口rename.py,对本地项目信息以及真实项目目录进行重命名
        :return:
        '''
        if self.current_project is '':
            QMessageBox.information(self,'提示','请先选择项目')
        else:
            self.rename=Rename(self.current_project)
            self.rename.newName_Signal.connect(self.__rename)
            self.rename.show()

        # pass

    def __rename(self,new_name):
        '''
        计算函数，该函数能实现将给定的项目原名称更改为新项目名字，首先对真实项目名称进行更改，然后更改数据库类的名称
        :param origin_name: 就是当前选中的项目
        :param new_name:
        :return: 注意改名完后，要刷新才行,还要注意本地数据库内容路径也要刷新
        '''
        real_project_path=self.getRealProjectPath(self.current_project)
        if real_project_path:#当存在时
            project_dir=os.path.dirname(real_project_path)
            new_project_path=os.path.join(project_dir,new_name)
            if self.projectCheck(self.PROJECT_INFO_PATH,new_name):#检查一下是不是重名
                QMessageBox.information(self,'提示','新命名项目已经存在')
            else: #当真的是可以用的非重名的名称时
                try:
                    os.rename(real_project_path,new_project_path)#重命名真实项目文件夹名称
                    project_info_path=os.path.join(self.PROJECT_INFO_PATH,self.current_project)

                    # self.updateProjectInfo_name_path(new_name, new_name)  # 因为在更新之前，名称已经被更换掉了，所以就用新名称
                    self.updateProjectInfo_name_path(self.current_project, new_name)
                    new_project_info_path=os.path.join(self.PROJECT_INFO_PATH,new_name)
                    os.rename(project_info_path, new_project_info_path)#重命名数据库项目名称

                    self.radio_project_list.remove(self.current_project)#移除在全局记录项目名称列表中的原名称
                    self.radio_project_list.append(new_name)

                    self.setRadioBtnList(self.radio_project_list)#更新视图

                except :
                    QMessageBox.information(self,'提示','原项目文件正在被操作')




    def getRealProjectPath(self,projectName):
        '''
        该函数可以作为通用函数，用来根据提供的项目名称来获取真实项目路径
        :param projectName:
        :return:
        '''
        project_info_path=os.path.join(self.PROJECT_INFO_PATH,projectName)
        real_project_path=''
        if os.path.exists(project_info_path):
            with open(project_info_path,'r',encoding='utf-8') as r:
                read=r.read()
                dic=eval(read)
                real_project_path=dic['project_path']

            return real_project_path

        else:
            QMessageBox.information(self,'提示','项目文件不存在，请检查')
            return False

    def __rightMenu(self):
        self.menu=QMenu()

        self.newAction=QAction(u'新建项目',self)
        self.newAction.triggered.connect(self._newBtn)
        self.menu.addAction(self.newAction)

        self.reAddAction=QAction(u'重匹配路径',self)
        self.reAddAction.triggered.connect(self._reAddBtn)
        self.menu.addAction(self.reAddAction)

        self.deleteAction=QAction(u'删除项目',self)
        self.deleteAction.triggered.connect(self.__deleteBtn)
        self.menu.addAction(self.deleteAction)

        self.renameAction=QAction(u'修改项目名称',self)
        self.renameAction.triggered.connect(self.renameBtn)
        self.menu.addAction(self.renameAction)

        self.refreshAction=QAction(u'刷新',self)
        self.refreshAction.triggered.connect(self.__refresh)
        self.menu.addAction(self.refreshAction)

        self.openAction=QAction(u'打开目录',self)
        self.openAction.triggered.connect(self.__open)
        self.menu.addAction(self.openAction)

        self.menu.exec_(QCursor.pos())

    def _newBtn(self):
        self.cp=CreateProject(self.PROJECT_INFO_PATH)
        self.cp.new_project_Signal.connect(self._addProject)
        self.cp.show()

    def _addProject(self,name):
        self.radio_project_list.append(name)
        self.setRadioBtnList(self.radio_project_list)
        self.__refresh()

    def _reAddBtn(self):
        '''
        该函数可以指认已存在的项目，将其加入到项目列表
        :return:
        '''
        dir = QFileDialog.getExistingDirectory(self, '选择文件夹')

        if dir:
            new_project_name=os.path.split(dir)[1]
            new_project_info_path = os.path.join(self.PROJECT_INFO_PATH, new_project_name)
            #{'project_name': 'X战警', 'project_path': 'F:/PycharmOut/BrickMover/Sample/Projects/X战警', 'project_type': 1}
            if new_project_name not in self.radio_project_list:
                self.radio_project_list.append(new_project_name)
                self.setRadioBtnList(self.radio_project_list)
                if not os.path.exists(new_project_info_path):
                    new_project_info={}
                    new_project_info['project_name']=new_project_name
                    new_project_info['project_path']=dir
                    new_project_info['project_type']=1
                    with open(new_project_info_path,'w',encoding='utf-8') as w:
                        w.write(str(new_project_info))
                print('add new project %s' % new_project_name)
            else:
                QMessageBox.information(self,'提示','该项目已经存在项目列表当中')





    def __deleteBtn(self):
        '''
        删除项目按钮
        :return:
        '''
        self.dw=DeleteWarn(0)
        self.dw.out_Signal.connect(self.__real_delete)
        self.dw.show()




    def __real_delete(self, back):
        if back==1:
            btn=self.focusWidget()
            current_project=btn.text()
            if current_project in self.radio_project_list:
                self.radio_project_list.remove(current_project)
                for i in range(self.scroll_layout.count()):
                    self.scroll_layout.itemAt(i).widget().deleteLater()

                #既然要删除，我们这里的删除是软删除，不直接删除原真实工程文件目录，只删除本地projects数据库中的项目记录
                self.__removeProject(current_project)

                self.setRadioBtnList(self.radio_project_list)
    def __removeProject(self,name):
        '''
        中间计算函数，不能用于外面调用
        :param name:
        :return:
        '''
        project_name_list=os.listdir(self.PROJECT_INFO_PATH)
        if name in project_name_list:
            project_info_path=os.path.join(self.PROJECT_INFO_PATH,name)
            os.remove(project_info_path)
            QMessageBox.information(self,'提示','删除成功')
        else:
            QMessageBox.information(self, '提示', '数据库中不存在该项目')

    def __refresh(self):
        '''
        刷新项目列表
        :return:
        '''
        print(self.PROJECT_INFO_PATH)
        name_list=os.listdir(self.PROJECT_INFO_PATH)
        self.setRadioBtnList(name_list)

    def __open(self):
        '''
        打开当前工程目录
        :return:
        '''
        btn=self.focusWidget()
        if isinstance(btn,QRadioButton) :
            # QMessageBox.information(self,'提示','鼠标请放在要打开的项目名称上')
        #else:
            choose_project=btn.text()
            choose_project_db_path=os.path.join(self.PROJECT_INFO_PATH,choose_project)
            str_read=''
            real_project_path=''
            with open(choose_project_db_path,'r',encoding='utf-8') as r:
                str_read=r.read()
            if str_read:
                real_project_path=eval(str_read)['project_path']
            try:
                sysstr = platform.system()
                if sysstr == "Windows":
                    os.startfile(real_project_path.replace('/','\\'))
                else:
                    os.startfile(real_project_path)

            except Exception as open_project_info_ERR:
                print(real_project_path)
                print(str(open_project_info_ERR))
                QMessageBox.information(self,'提示','原工程路径与本地记录不符,请重建工程')



    def writeProjectInfo(self,project_name,project_type,project_path):
        '''
        该函数实现将已经创建的项目信息写入到本地Project_Info当中。这样可以在主界面中一开始读取这些已有的项目
        :return:
        '''
        if not self.projectCheck(self.PROJECT_INFO_PATH,project_name):
            # project_info=[project_name,projectType,projectPath]

            project_info={}
            project_info_path=os.path.join(self.PROJECT_INFO_PATH,project_name)
            project_info['project_name']=project_name
            project_info['project_type']=project_type
            project_info['project_path']=project_path
            # with open(self.PROJECT_INFO_PATH,'a','utf-8') as f: #不需要用csv,项目不多，就一个项目一个文件干脆利落
            #     csv_writer=csv.writer(f,dialect='excel')

            with open(project_info_path,'w',encoding='utf-8') as w:
                w.write(str(project_info))
        else:
            QMessageBox.information(self,'注意','该项目已存在')


    def updateProjectInfo_name_path(self,project_name,new_project_name):
        '''
        该函数是实现当给定原项目名称与新项目名称，更新项目里的project_name,与project_path
        :param project_name: 原项目名称,注意这里也可能是重新改名后的项目名称，只是里面内容没改
        :param new_project_name: 新项目名称
        :return:
        '''
        project_info_path=os.path.join(self.PROJECT_INFO_PATH,project_name)
        new_project_info_path=os.path.join(self.PROJECT_INFO_PATH,new_project_name)
        newDic = {}
        with open(project_info_path,'r',encoding='utf-8') as r:
            read=r.read()
            dic=eval(read)

            newDic['project_name']=new_project_name
            newDic['project_type']=dic['project_type']
            newDic['project_path']=new_project_info_path

        with open(new_project_info_path,'w',encoding='utf-8') as w:
            w.write(str(newDic))






    def projectCheck(self,project_info_path,projectName):
        '''
        该函数用来检测要创建的项目是否已经存在
        :param project_info_path:
        :param projectName:
        :return:
        '''
        project_list=os.listdir(project_info_path)
        if projectName not in project_list:
            return False
        else:
            return True













if __name__ == '__main__':
    app=QApplication()
    R=RadioWidget()
    nameList=['a','b','c','d','e']
    R.setRadioBtnList(nameList)
    R.show()
    sys.exit(app.exec_())